<template>
  <el-dialog
    :title="title"
    :visible.sync="actionOpen"
    width="500px"
    append-to-body
    @update:visible="$emit('update:visible', $event)"
  >
    <el-form
      ref="actionForm"
      :model="actionForm"
      :rules="actionRules"
      label-width="120px"
    >
      <el-form-item label="动作类型" prop="type">
        <el-select v-model="actionForm.type" placeholder="请选择动作类型">
          <el-option label="设备输出" value="deviceOutput" />
          <el-option label="上报告警" value="reportError" />
          <el-option label="上报通知" value="reportNotice" />
        </el-select>
      </el-form-item>
      <el-form-item label="产品Key" prop="productId">
        <el-select
          v-model="actionForm.productId"
          placeholder="请选择产品"
          @change="handleProductChange"
        >
          <el-option
            v-for="item in productOptions"
            :key="item.productId"
            :label="item.productName"
            :value="item.productId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="设备ID" prop="deviceId">
        <el-select
          v-model="actionForm.deviceId"
          placeholder="请选择设备"
          :disabled="!actionForm.productId"
        >
          <el-option
            v-for="item in deviceOptions"
            :key="item.deviceId"
            :label="item.deviceName"
            :value="item.deviceId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="服务/方法/告警" prop="serviceMethod">
        <el-input
          v-model="actionForm.serviceMethod"
          placeholder="请输入服务ID/方法ID/告警ID"
        />
      </el-form-item>
      <el-form-item label="服务/方法/告警名称" prop="serviceMethodName">
        <el-input
          v-model="actionForm.serviceMethodName"
          placeholder="请输入服务名/方法名/告警名称"
        />
      </el-form-item>
      <el-form-item label="参数" prop="serviceParams">
        <el-input
          v-model="actionForm.serviceParams"
          type="textarea"
          placeholder="请输入参数（可选）"
        />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitActionForm">确 定</el-button>
      <el-button @click="cancelAction">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {
  addIotRulesAction,
  updateIotRulesAction,
  selectIotRulesActionByActionId,
} from "@/api/system/iot/action";
import { findProductConfigList } from "@/api/system/iot/product";
import { listDevice } from "@/api/system/iot/device";

export default {
  props: {
    visible: {
      type: Boolean,
      required: true,
    },
    ruleId: {
      type: [String, Number],
      required: true,
    },
    action: {
      type: Object,
      default: () => ({}),
    },
    title: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      actionOpen: this.visible,
      actionForm: {
        actionId: undefined,
        ruleId: this.ruleId,
        type: undefined,
        productId: undefined,
        deviceId: undefined,
        serviceMethod: undefined,
        serviceMethodName: undefined,
        serviceParams: undefined,
      },
      productOptions: [],
      deviceOptions: [],
      actionRules: {
        type: [
          { required: true, message: "请选择动作类型", trigger: "change" },
        ],
        productId: [
          { required: true, message: "请选择产品Key", trigger: "change" },
        ],
        deviceId: [
          { required: true, message: "请选择设备ID", trigger: "change" },
        ],
        serviceMethod: [
          {
            required: true,
            message: "请输入服务ID/方法ID/告警ID",
            trigger: "blur",
          },
        ],
        serviceMethodName: [
          {
            required: true,
            message: "请输入服务名/方法名/告警名称",
            trigger: "blur",
          },
        ],
      },
    };
  },
  watch: {
    visible(newVal) {
      this.actionOpen = newVal;
      if (newVal) {
        this.loadProductOptions();
        if (this.action.actionId) {
          selectIotRulesActionByActionId(this.action.actionId).then(
            (response) => {
              if (response.data.productId) {
                this.handleProductChange(response.data.productId);
              }
              setTimeout(() => {
                this.actionForm = response.data;
              }, 100);
            }
          );
        } else {
          this.resetActionForm();
        }
      }
    },
  },
  methods: {
    handleProductChange(productId) {
      this.actionForm.deviceId = undefined;
      this.deviceOptions = [];
      if (productId) {
        listDevice({ productId: productId }).then((response) => {
          this.deviceOptions = response.rows;
        });
      }
    },
    loadProductOptions() {
      findProductConfigList().then((response) => {
        this.productOptions = response.data;
      });
    },
    submitActionForm() {
      this.$refs["actionForm"].validate((valid) => {
        if (valid) {
          if (this.actionForm.actionId) {
            updateIotRulesAction(this.actionForm).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.actionOpen = false;
              this.$emit("update:visible", false);
              this.$emit("action-updated");
            });
          } else {
            addIotRulesAction(this.actionForm).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.actionOpen = false;
              this.$emit("update:visible", false);
              this.$emit("action-updated");
            });
          }
        }
      });
    },
    cancelAction() {
      this.actionOpen = false;
      this.$emit("update:visible", false);
      this.resetActionForm();
    },
    resetActionForm() {
      this.actionForm = {
        actionId: undefined,
        ruleId: this.ruleId,
        type: undefined,
        productId: undefined,
        deviceId: undefined,
        serviceMethod: undefined,
        serviceMethodName: undefined,
        serviceParams: undefined,
      };
      this.$refs["actionForm"] && this.$refs["actionForm"].resetFields();
    },
  },
};
</script>
